<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Test exporting keys with various usages to JWK.");

jsTestIsAsync = true;

var extractable = true;

var aesKeyAsArrayBuffer = Base64URL.parse("jnOw99oOZFLIEPMrgJB55Q");
var hmacKeyAsArrayBuffer = Base64URL.parse("ahjkn-_387fgnsibf23qsvahjkn-_387fgnsibf23qs");

function testWithAESCBC(usages, expectedKeyOps)
{
   return crypto.subtle.importKey("raw", aesKeyAsArrayBuffer, {name: "AES-CBC"}, extractable, usages).then(function(result) {
        return crypto.subtle.exportKey("jwk", result);
    }).then(function(result) {
        jwk = result;
        debug(usages + ":");
        shouldBe("jwk.use", "undefined");
        shouldBe("jwk.key_ops", JSON.stringify(expectedKeyOps));
        debug("");
    });
}

function testWithHMAC(usages, expectedKeyOps)
{
    return crypto.subtle.importKey("raw", hmacKeyAsArrayBuffer, {name: 'hmac', hash: {name: 'sha-256'}}, extractable, usages).then(function(result) {
        return crypto.subtle.exportKey("jwk", result);
    }).then(function(result) {
        jwk = result;
        debug(usages + ":");
        shouldBe("jwk.use", "undefined");
        shouldBe("jwk.key_ops", JSON.stringify(expectedKeyOps));
        debug("");
    });
}

Promise.all([
    testWithAESCBC(["encrypt"], ["encrypt"]),
    testWithAESCBC(["decrypt"], ["decrypt"]),
    testWithAESCBC(["encrypt", "decrypt"], ["encrypt", "decrypt"]),
    testWithAESCBC(["wrapKey"], ["wrapKey"]),
    testWithAESCBC(["unwrapKey"], ["unwrapKey"]),
    testWithAESCBC(["wrapKey", "unwrapKey"], ["wrapKey", "unwrapKey"]),
    testWithAESCBC(["encrypt", "decrypt", "wrapKey"], ["encrypt", "decrypt", "wrapKey"]),
    testWithAESCBC(["encrypt", "decrypt", "wrapKey", "unwrapKey"], ["encrypt", "decrypt", "wrapKey", "unwrapKey"]),
    testWithHMAC(["sign"], ["sign"]),
    testWithHMAC(["verify"], ["verify"]),
    testWithHMAC(["sign", "verify"], ["sign", "verify"]),
]).then(finishJSTest, failAndFinishJSTest);
</script>

</body>
</html>
